/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.springmvc.response;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import org.springframework.lang.Nullable;

import java.util.Optional;

/**
 * 返回结果
 * @author moon
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class R<T> {

	private int code;
	/** 返回的用户展示的详细信息*/
	private String msg;
	/** 返回的具体数据*/
	private T data;
	
	public static <T> R<T> status(Boolean status) {
		if(status) {
			return success();
		}
		return fail(RCode.FAIL.getMsg());
	}

	public static <T> R<T> fail(String msg) {
		return fail(RCode.FAIL.getCode(), msg);
	}
	
	public static <T> R<T> fail(int code, String msg) {
		R<T> r = new R<>();
		r.setCode(code);
		r.setMsg(msg);
		return r;
	}
	public static <T> R<T> fail(RCode code) {
		return fail(code.getCode(),code.getMsg());
	}

	public static <T> R<T> success() {
		R<T> r = new R<>();
		r.setCode(RCode.SUCCESS.getCode());
		r.setMsg(RCode.SUCCESS.getMsg());
		return r;
	}

	public static <T> R<T> success(T t) {
		return success(t,RCode.SUCCESS.getCode(),RCode.SUCCESS.getMsg());
	}

	public static <T> R<T> success(T t,int code, String msg) {
		R<T> r = new R<>();
		r.setCode(code);
		r.setData(t);
		r.setMsg(msg);
		return r;
	}

	/**
	 *  服务熔断标准返回
	 */
	public static <T> R<T> feign(T t){
		return success(t,RCode.FEIGN_ERROR.getCode(),RCode.FEIGN_ERROR.getMsg());
	}

	/**
	 *  系统限流标准返回
	 */
	public static <T> R<T> limit(T t){
		return success(t,RCode.FLOW_LIMITING.getCode(),RCode.FLOW_LIMITING.getMsg());
	}

	/**
	 * 是否正确返回
	 */
	public static boolean isSuccess(@Nullable R<?> result) {
		return (Boolean) Optional.ofNullable(result).map((x) -> {
			return RCode.SUCCESS.getCode()==x.getCode();
		}).orElse(Boolean.FALSE);
	}
}